package com.aiti.lulian.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.EnterpriseDto;
import com.aiti.lulian.dto.WeChatUserCardHolderDto;
import com.aiti.lulian.entity.CardEnterpriseUserData;
import com.aiti.lulian.entity.CardOperationLog;
import com.aiti.lulian.service.CardEnterpriseUserDataService;
import com.aiti.lulian.service.ICardOperationLogService;
import com.aiti.lulian.vo.CardEnterpriseUserDataByBaseIdVo;
import com.aiti.lulian.vo.CardEnterpriseUserDataVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Api(tags = "员工名片控制层")
@RestController
@RequestMapping("/userCard")
public class CardEnterpriseUserDataController extends WebController<CardEnterpriseUserData> {

    private final Logger logger = LoggerFactory.getLogger(CardEnterpriseUserDataController.class);

    @Autowired
    private CardEnterpriseUserDataService cardEnterpriseUserDataService;

    @Autowired
    private ICardOperationLogService cardOperationLogService;

    /**
     * 员工名片统计
     * @param vo
     * @return
     */
    @GetMapping("/statistic")
    public Message statistic(CardEnterpriseUserDataVo vo){
        Page<CardEnterpriseUserData> page = startPage();

        List<CardEnterpriseUserData> result = cardEnterpriseUserDataService.enterpriseUserDataCount(page, vo);
        return this.Success(this.getPageResult(result, (int)page.getTotal()));

    }

    /**
     * @Author WongMz
     * @CreateDate 2024-09-11
     * @Description: 根据用户Id查询员工名片数据
     */
    @ApiOperation("根据用户Id查询员工名片数据")
    @GetMapping("/{userId}")
    public Message queryDetailsByUserId(@PathVariable("userId") String userId) {
        try {
            if (StrUtil.isBlank(userId)) {
                logger.error("【queryDetailsByUserId】方法查询异常：===》入参异常");
                return Fail("入参异常！");
            }
            List<CardEnterpriseUserData> list = cardEnterpriseUserDataService.list(new LambdaQueryWrapper<CardEnterpriseUserData>()
                    .eq(CardEnterpriseUserData::getUserId, userId).eq(CardEnterpriseUserData::getIsDelete, "0"));
            if (list.size() > 1) {
                logger.error("id为【" + userId + "】的用户名片记录存在多条，请及时进行处理！");
                throw new RuntimeException("名片记录存在多条，请联系平台工作人员进行处理");
            } else if (list == null || list.isEmpty()){
                throw new RuntimeException("名片记录尚未初始化，请联系平台工作人员进行处理");
            } else {
                return Success(list.get(0));
            }
        } catch (Exception e) {
            logger.error("【queryDetailsByUserId】方法查询异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

//    该接口的业务逻辑已在manage-subservice服务中的subUser/app/getInfoByUserName接口中存在，因此不再使用此接口
//    /**
//     * @Author WongMz
//     * @CreateDate 2024-09-27
//     */
//    @ApiOperation("根据用户Id查询其员工名片是否已初始化")
//    @GetMapping("/exist/{userId}")
//    public Message queryIsExistByUserId(@PathVariable("userId") String userId) {
//        try {
//            if (StrUtil.isBlank(userId)) {
//                logger.error("【queryIsExistByUserId】方法查询异常：===》入参异常");
//                return Fail("入参异常！");
//            }
//            boolean res;
//            List<CardEnterpriseUserData> list = cardEnterpriseUserDataService.list(new LambdaQueryWrapper<CardEnterpriseUserData>()
//                    .eq(CardEnterpriseUserData::getUserId, userId).eq(CardEnterpriseUserData::getIsDelete, "0"));
//            if (list == null || list.isEmpty()) {
//                res = false;
//                //若不存在，则初始化出其名片数据
//                CardEnterpriseUserData cardEnterpriseUserData = CardEnterpriseUserData.builder().userId(userId).creator(userId).source("3").build();
//                LambdaQueryWrapper<LuLianEnterpriseUser> wrapper = new LambdaQueryWrapper<>();
//                wrapper.eq(LuLianEnterpriseUser::getUserId, userId);
//                List<LuLianEnterpriseUser> enterpriseUserList = luLianEnterpriseUserService.list(wrapper);
//                if (enterpriseUserList != null && enterpriseUserList.size() > 1) {
//                    logger.error("=========> id为【{}】的用户企业关联数据存在多条，请及时处理！ <=========", userId);
//                    throw new RuntimeException("您的账号关联了多个企业，请联系平台人员进行处理");
//                } else if (enterpriseUserList == null || enterpriseUserList.isEmpty()) {
//                    cardEnterpriseUserData.setEnterpriseId(null);
//                } else {
//                    cardEnterpriseUserData.setEnterpriseId(enterpriseUserList.get(0).getEnterpriseId());
//                }
//                cardEnterpriseUserDataService.save(cardEnterpriseUserData);
//            } else if (list.size() > 1) {
//                logger.error("=========> id为【{}】的用户名片记录存在多条，请及时进行处理！ <=========", userId);
//                throw new RuntimeException("名片记录存在多条，请联系平台工作人员进行处理");
//            } else {
//                res = true;
//            }
//            return Success(res);
//        } catch (Exception e) {
//            logger.error("【queryIsExistByUserId】方法查询异常：===》" + e);
//            return Fail(e.getMessage());
//        }
//    }

    @ApiOperation(value = "查询员工名片-名片夹列表")
    @GetMapping("findUserCardandCardHolder")
    public Message findUserCardandCardHolder(WeChatUserCardHolderDto weChatUserCardHolderDto){
        try {
            return Success(cardEnterpriseUserDataService.findUserCardandCardHolder(weChatUserCardHolderDto));
        }catch (Exception e){
            logger.error("查询异常：===》" + e);
            return Error(e.getMessage());
        }
    }

    @ApiOperation(value = "删除收藏的名片")
    @DeleteMapping("/deleteCardHolder")
    public Message deleteCardHolder(@RequestParam("baseId") String baseId){
        return cardEnterpriseUserDataService.deleteCardHolder(baseId);
    }

    /**
     * @param currentUserId 当值为 "isNotLogin" 时，表示当前预览人未登录
     * @param from from代表此接口被调用的来源，"1"表示访客量计数，"2"表示访客量不计数
     * @param loginCode 当预览人未登录时，前端会传来一个属于预览人当前所登录微信的一个code码，该码用于后端通过请求微信端接口从而获取该预览人的微信数据（唯一标识）
     */
    //根据名片id查询员工名片信息
    @ApiOperation(value = "查询员工名片信息")
    @GetMapping("findUserCardInfo")
    public Message findUserCardInfo(@RequestParam(value = "userId") String userId,
                                    @RequestParam(value = "currentUserId", required = false) String currentUserId,
                                    @RequestParam(value = "from") String from,
                                    @RequestParam(value = "loginCode", required = false) String loginCode,
                                    @RequestParam(value = "source", required = false) String source) {
        try {
            CardEnterpriseUserDataByBaseIdVo cardandCardHolder = cardEnterpriseUserDataService.findUserCardInfoByBaseId(userId, currentUserId, from, loginCode, source);
            logger.info("预览页接口返回的数据为：{}", cardandCardHolder);
            return Success(cardandCardHolder);
        }catch (Exception e){
            logger.error("查询异常：===》" + e);
            return Error(e.getMessage());
        }
    }

    @GetMapping("/updateOrSaveStaffSendCardCount")
    public Message updateOrSaveStaffSendCardCount(CardEnterpriseUserData cardEnterpriseUserData){
        if(StringUtils.isBlank(cardEnterpriseUserData.getEnterpriseId()) || StringUtils.isBlank(cardEnterpriseUserData.getUserId())){
            return Message.fail("没有找到企业Id或用户Id");
        }
        List<CardEnterpriseUserData> list = cardEnterpriseUserDataService.list(new QueryWrapper<CardEnterpriseUserData>()
                .eq("is_delete", "0")
                .eq("user_id", cardEnterpriseUserData.getUserId()));
        if(list != null && list.size() > 1){
            return Message.fail("名片数据出现异常：数量");
        } else if (list != null && list.size() == 0) {
            CardEnterpriseUserData build = CardEnterpriseUserData.builder().build();
            build.setBaseId(IdUtil.simpleUUID());
            build.setBaseCreateTime(new Date());
            build.setBaseUpdateTime(new Date());
            build.setPubCount(1L);
            build.setIsDelete("0");
            build.setSource("3");
            build.setEnterpriseId(cardEnterpriseUserData.getEnterpriseId());
            build.setUserId(cardEnterpriseUserData.getUserId());
            build.setCreator(cardEnterpriseUserData.getUserId());
            cardEnterpriseUserDataService.save(build);
        }else{
            CardEnterpriseUserData dbData = list.get(0);
            dbData.setPubCount(dbData.getPubCount() + 1L);
            dbData.setBaseUpdateTime(new Date());
            cardEnterpriseUserDataService.updateById(dbData);
        }
        //构建转发日志数据
        CardOperationLog cardOperationLog = CardOperationLog.builder()
                .userId(cardEnterpriseUserData.getUserId())
                .enterpriseId(cardEnterpriseUserData.getEnterpriseId())
                .type("1")
                .build();
        //新增转发日志
        cardOperationLogService.save(cardOperationLog);
        return Message.success();
    }

    @ApiOperation("创建员工名片和名片访问记录")
    @PostMapping("/access")
    public Message createCardAndAccessRecord(@RequestParam("userId") String userId,
                                             @RequestParam(value = "enterpriseId", required = false) String enterpriseId,
                                             @RequestParam("source") String source,
                                             @RequestParam("creator") String creator) {
        try {
            if (StrUtil.isBlank(userId)) {
                logger.error("【createCardAndAccessRecord】方法新增异常：===》入参异常");
                return Fail("入参异常！");
            }
            return cardEnterpriseUserDataService.createCardAndAccessRecord(userId, enterpriseId, source, creator);
        } catch (Exception e) {
            logger.error("【createCardAndAccessRecord】方法新增异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

    @ApiOperation("删除员工名片、名片访问记录以及名片收藏夹数据")
    @DeleteMapping("/access")
    public Message deleteCardAndAccessAndHolder(@RequestParam("userId") String userId,
                                             @RequestParam("enterpriseId") String enterpriseId) {
        try {
            if (StrUtil.isBlank(userId) || StrUtil.isBlank(enterpriseId)) {
                logger.error("【deleteCardAndAccessAndHolder】方法删除异常：===》入参异常");
                return Fail("入参异常！");
            }
            cardEnterpriseUserDataService.deleteCardAndAccessAndHolder(userId, enterpriseId);
            return Success("删除成功！");
        } catch (Exception e) {
            logger.error("【deleteCardAndAccessAndHolder】方法删除异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

    //收藏名片
    @ApiOperation(value = "收藏名片")
    @PostMapping("/collectUserCard")
    public Message collectUserCard(@RequestBody WeChatUserCardHolderDto WeChatUserCardHolderDto){
        return cardEnterpriseUserDataService.collectUserCard(WeChatUserCardHolderDto);
    }

    @GetMapping("/saveOrUpdateCardEnterpriseUserData")
    public Message saveOrUpdateCardEnterpriseUserData(@RequestParam("userId") String userId, @RequestParam("enterpriseId")String enterpriseId){
        System.out.println("========>"+userId);
        System.out.println("========>"+enterpriseId);
        if(StrUtil.isBlank(userId) || StrUtil.isBlank(enterpriseId)){
            return Message.fail("用户Id或企业Id没有找到");
        }
        QueryWrapper<CardEnterpriseUserData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", "0");
        queryWrapper.eq("user_id", userId);
        List<CardEnterpriseUserData> list = cardEnterpriseUserDataService.list(queryWrapper);
        if(list != null && list.size() > 1){
            return Message.fail("1 to n");
        }
        if(list == null || list.size() == 0){
            CardEnterpriseUserData build = CardEnterpriseUserData.builder()
                    .baseId(IdUtil.simpleUUID())
                    .userId(userId)
                    .enterpriseId(enterpriseId)
                    .baseCreateTime(new Date())
                    .baseUpdateTime(new Date())
                    .creator(userId)
                    .source("3")
                    .isDelete("0")
                    .build();
            cardEnterpriseUserDataService.save(build);
        }else {
            CardEnterpriseUserData dbData = list.get(0);
            dbData.setBaseUpdateTime(new Date());
            dbData.setEnterpriseId(enterpriseId);
            dbData.setUpdateBy(userId);
            cardEnterpriseUserDataService.updateById(dbData);
        }
        return Message.success();
    }

    //我发布的
    //传参 当前登录人的员工id
    @ApiOperation(value = "名片首页-我发布的")
    @PutMapping("myPublishCount")
    public Message myPublishCount(WeChatUserCardHolderDto weChatUserCardHolderDto){
        try {
            return cardEnterpriseUserDataService.myPublishCount(weChatUserCardHolderDto);
        }catch (Exception e){
            logger.error("名片首页-发布异常：===》" + e);
            return Error(e.getMessage());
        }
    }

    @ApiOperation(value = "新增（manage_subService远程调用）")
    @PostMapping("add")
    public Message add(@RequestParam("userId") String userId,
                       @RequestParam(value = "enterpriseId", required = false) String enterpriseId,
                       @RequestParam("source") String source){
        try {
            CardEnterpriseUserData one = cardEnterpriseUserDataService.getOne(new LambdaQueryWrapper<CardEnterpriseUserData>()
                    .eq(CardEnterpriseUserData::getUserId, userId)
                    .eq(CardEnterpriseUserData::getIsDelete, "0"));
            if (one == null) {
                return cardEnterpriseUserDataService.add(userId, enterpriseId, source);
            } else {
                if (StrUtil.isNotBlank(enterpriseId) && (! StrUtil.equals(one.getEnterpriseId(), enterpriseId))) {
                    cardEnterpriseUserDataService.update(new LambdaUpdateWrapper<CardEnterpriseUserData>().eq(CardEnterpriseUserData::getUserId, userId)
                            .eq(CardEnterpriseUserData::getIsDelete, "0")
                            .set(CardEnterpriseUserData::getEnterpriseId, enterpriseId));
                }
                return Success();
            }
        } catch (Exception e) {
            logger.error("【add】方法新增异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

    /**
     * 用于manage-subservice远程调用
     */
    @GetMapping("/updateCardEnterpriseUserData")
    public Message updateCardEnterpriseUserData(@RequestParam("userId") String userId, @RequestParam("enterpriseId")String enterpriseId) {
        LambdaQueryWrapper<CardEnterpriseUserData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CardEnterpriseUserData::getIsDelete, "0");
        wrapper.eq(CardEnterpriseUserData::getUserId, userId);
        List<CardEnterpriseUserData> list = cardEnterpriseUserDataService.list(wrapper);
        if (list.size() > 1) {
            return Message.fail("1 to n");
        } else if (list.size() == 1) {
            CardEnterpriseUserData dbData = list.get(0);
            dbData.setBaseUpdateTime(new Date());
            dbData.setEnterpriseId(enterpriseId);
            dbData.setUpdateBy(userId);
            cardEnterpriseUserDataService.updateById(dbData);
        }
        return Message.success();
    }

    @ApiOperation(value = "设置是否允许员工自定义名片样式")
    @PutMapping("setIsCustom")
    public Message setIsCustom(@RequestBody EnterpriseDto enterpriseDto){
        String userId = enterpriseDto.getUserId();
        if (StrUtil.isBlank(userId)) {
            userId = findUserId();
            if (StrUtil.isBlank(userId)) {
                return Fail("请先登录");
            }
            enterpriseDto.setUserId(userId);
        }
        return cardEnterpriseUserDataService.setIsCustom(enterpriseDto);
    }

    @ApiOperation(value = "通过用户手机号判断该用户是否已创建名片")
    @GetMapping("/hasCard")
    public Message hasCard(@RequestParam("phoneNumber") String phoneNumber){
        return Success(cardEnterpriseUserDataService.hasCard(phoneNumber));
    }
}